<?php


namespace app\model;


use think\facade\Db;

class Member extends BaseModel
{
    //表名
    protected $table = 'member';

    //主键
    protected $pk = 'member_id';

    // 设置字段信息
    protected $schema = [
        'uid'               => 'int',
        'register_source'   => 'tinyint',   //注册来源：0管理员添加 1手机号 2邮箱 3用户名 4qq 5微信
        'register_client'   => 'tinyint',   //注册客户端：1pc端 2移动端 3安卓App 4IOSApp 5微信小程序
        'nickname'          => 'varchar',   //昵称
        'username'          => 'varchar',   //用户名
        'gender'            => 'tinyint',   //用户性别 0-female 1-male
        'birthday'          => 'int',       //生日
        'signature'         => 'varchar',   //用户个人签名
        'mobile'            => 'int',       //手机号（唯一）
        'email'             => 'varchar',   //邮箱唯一
        'face'              => 'varchar',   //头像
        'face200'           => 'varchar',   //头像200
        'srcface'           => 'varchar',   //原图头像
        'create_time'       => 'int',       //创建时间
        'update_time'       => 'int',       //更新时间
    ];

    protected $markSchema=[
        'id' => 'int',
        'member_id' => 'int',
        'token' => 'varchar',        //账户登录名 保存手机号、邮箱账户、微信token和QQ Token
        'password' => 'varchar',     //账户登录口令  只有手机号登录和邮箱登录才有密码
        'type' => 'tinyint',                //账户类型：1手机号，2邮箱，3用户名，4qq，5微信，6微博
        'create_time' => 'varchar',
    ];

    /**
     * 密码加密
     * @param $str 加密字符串
     * @return string
     */
    public function pwdMd5($str){
        return md5('hx_' . md5($str) . '_2019');
    }

    public function add($input)
    {
        $data=[
            'register_source'   => $input['register_source'],   //注册来源：1手机号 2邮箱 3用户名 4qq 5微信
            'register_client'   => $input['register_client'],   //注册客户端：1pc端 2移动端 3安卓App 4IOSApp 5微信小程序
            'nickname'          => $input['nickname'],   //昵称
            'gender'            => $input['gender'],   //用户性别 1-female 2-male
            'birthday'          => $input['gender'],       //生日
            'signature'         => $input['signature'],   //用户个人签名
            'mobile'            => $input['mobile'],       //手机号（唯一）
            'email'             => $input['email'],   //邮箱唯一
            'create_time'       => $input['create_time'],       //创建时间
        ];
        $msg = Db::table($this->table)->insert($data);
        if(!$msg){
            return false;
        }
        return true;
    }

    /**
     * 用户名注册
     * @param $username 用户名
     * @param $password 密码
     * @param $regClient 注册客户端
     * @param $regIp 注册ip
     * @return bool
     */
    public function usernameReg($username,$password,$regClient,$regIp){
        $condition=[
            'token' => $username,
            'type' => 3,
        ];
        if(Db::table('member_mark')->where($condition)->count() > 0){
            $this->setError(3001,'该用户已存在！');
            return false;
        }
        $t = time();
        $data=[
            'register_source'   => 1,   //注册来源：1手机号 2邮箱 3用户名 4qq 5微信
            'register_client'   => $regClient,   //注册客户端：1pc端 2移动端 3安卓App 4IOSApp 5微信小程序
            'username'            => $username,       //用户名
            'nickname'            => $username,       //默认昵称为用户名
            'create_time'       => $t,       //创建时间
            'register_ip'       => $regIp,       //注册ip
        ];
        try{
            $this->startTrans();
            $id = Db::table($this->table)->insertGetId($data);
            if(!$id){
                $this->setError(3010,'用户注册失败！');
                $this->rollback();
                return false;
            }
            $msg = Db::table('member_mark')->insert([
                'member_id' => $id,
                'token' => $username,
                'type' => 3,
                'password' => $this->pwdMd5($password),
                'create_time' => $t,
            ]);
            if(!$msg){
                $this->setError(3011,'用户注册失败！');
                $this->rollback();
                return false;
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->setError(9999,'用户注册失败！');
            $this->rollback();
            return false;
        }
    }

    /**
     * 手机注册
     * @param $phone 手机号
     * @param $password 密码
     * @param $regClient 注册客户端
     * @param $regIp 注册ip
     * @return bool|int|string 成功返回member_id
     */
    public function phoneReg($phone,$password,$regClient,$regIp){
        $condition=[
            'token' => $phone,
            'type' => 1,
        ];
        if(Db::table('member_mark')->where($condition)->count() > 0){
            $this->setError(3001,'该手机号已被注册！');
            return false;
        }
        $t = time();
        $data=[
            'register_source'   => 1,   //注册来源：1手机号 2邮箱 3用户名 4qq 5微信
            'register_client'   => $regClient,   //注册客户端：1pc端 2移动端 3安卓App 4IOSApp 5微信小程序
            'mobile'            => $phone,       //手机号（唯一）
            'nickname'          => $phone,       //默认昵称为手机号
            'create_time'       => $t,       //创建时间
            'register_ip'       => $regIp,       //注册ip
        ];
        try{
            $this->startTrans();
            $id = Db::table($this->table)->insertGetId($data);
            if(!$id){
                $this->setError(3010,'手机用户注册失败！');
                $this->rollback();
                return false;
            }
            $msg = Db::table('member_mark')->insert([
                'member_id' => $id,
                'token' => $phone,
                'type' => 1,
                'password' => $this->pwdMd5($password),
                'create_time' => $t,
            ]);
            if(!$msg){
                $this->setError(3011,'手机用户注册失败！');
                $this->rollback();
                return false;
            }
            $this->commit();
            return $id;
        }catch (\Exception $e){
            $this->setError(9999,'手机用户注册失败！'.$e->getMessage());
            $this->rollback();
            return false;
        }
    }

    /**
     * 邮箱注册
     * @param $email 手机号
     * @param $password 密码
     * @param $regClient 注册客户端
     * @param $regIp 注册ip
     * @return bool
     */
    public function emilReg($email,$password,$regClient,$regIp){
        $condition=[
            'token' => $email,
            'type' => 1,
        ];
        if(Db::table('member_mark')->where($condition)->count() > 0){
            $this->setError(3001,'该用户已存在！');
            return false;
        }
        $t = time();
        $data=[
            'register_source'   => 2,   //注册来源：1手机号 2邮箱 3用户名 4qq 5微信
            'register_client'   => $regClient,   //注册客户端：1pc端 2移动端 3安卓App 4IOSApp 5微信小程序
            'email'             => $email,       //邮箱（唯一）
            'nickname'          => $email,       //默认昵称为邮箱
            'create_time'       => $t,       //创建时间
            'register_ip'       => $regIp,       //注册ip
        ];
        try{
            $this->startTrans();
            $id = Db::table($this->table)->insertGetId($data);
            if(!$id){
                $this->setError(3010,'用户注册失败！');
                $this->rollback();
                return false;
            }
            $msg = Db::table('member_mark')->insert([
                'member_id' => $id,
                'token' => $email,
                'type' => 1,
                'password' => $this->pwdMd5($password),
                'create_time' => $t,
            ]);
            if(!$msg){
                $this->setError(3011,'用户注册失败！');
                $this->rollback();
                return false;
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->setError(9999,'用户注册失败！');
            $this->rollback();
            return false;
        }
    }


    /**
     * 用户绑定手机号
     * @param $memberId
     * @param $phone
     * @return bool
     */
    public function phoneBind($memberId, $phone){
        try{
            $this->startTrans();
            $id = Db::table($this->table)->where(['member_id'=>$memberId])->update(['mobile'=>$phone]);
            if(!$id){
                $this->setError(3030,'添加手机号失败！');
                $this->rollback();
                return false;
            }
            $condition=[
                ['member_id', '=', $memberId],
                ['type', 'in', [2,3]],
                ['password', '!=', '']
            ];
            $markData = Db::table('member_mark')->field('password')->where($condition)->find();
            $data = [
                'member_id' => $id,
                'token' => $phone,
                'type' => 1,
                'password' => '',
                'create_time' => time(),
            ];
            if(!empty($markData['password'])){
                $data['password'] = $markData['password'];
            }
            $msg = Db::table('member_mark')->insert($data);
            if(!$msg){
                $this->setError(3031,'添加手机号失败！');
                $this->rollback();
                return false;
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->setError(9999,'添加手机号失败！');
            $this->rollback();
            return false;
        }
    }

    /**
     * 用户绑定邮箱
     * @param $memberId
     * @param $email
     * @return bool
     */
    public function emailBind($memberId, $email){
        try{
            $this->startTrans();
            $id = Db::table($this->table)->where(['member_id'=>$memberId])->update(['email'=>$email]);
            if(!$id){
                $this->setError(3020,'添加邮箱失败！');
                $this->rollback();
                return false;
            }
            $condition=[
                ['member_id', '=', $memberId],
                ['type', 'in', [1,3]],
                ['password', '!=', '']
            ];
            $markData = Db::table('member_mark')->field('password')->where($condition)->find();
            $data = [
                'member_id' => $id,
                'token' => $email,
                'type' => 2,
                'password' => '',
                'create_time' => time(),
            ];
            if(!empty($markData['password'])){
                $data['password'] = $markData['password'];
            }
            $msg = Db::table('member_mark')->insert($data);
            if(!$msg){
                $this->setError(3021,'添加邮箱失败！');
                $this->rollback();
                return false;
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->setError(9999,'添加邮箱失败！');
            $this->rollback();
            return false;
        }
    }





    //-----------------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------------
    //-------------------------------------------------        用户数据       ------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------------


    /**
     * 获取用户列表
     * @param $where
     * @param int $limitLength
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function memberList($where,$limitLength=50){
        $condition=[];
        if (!empty($where['username'])){
            $condition[]=['username', '=', $where['username']];
        }
        if (!empty($where['mobile'])){
            $condition[]=['mobile', '=', $where['mobile']];
        }
        if (!empty($where['email'])){
            $condition[]=['email', '=', $where['email']];
        }
        $list = Db::table($this->table)
            ->field('*')
            ->where($condition)
            ->paginate($limitLength);
        // 获取总记录数
        $data=[
            'count' => $list->total(),
            'data' => $list->items(),
            'limit' => $limitLength,
            'currentPage' => $list->currentPage(),
        ];
        return $data;
    }

    /**
     * 添加用户
     * @param $params
     * @return bool
     */
    public function addMember($params){
        $data=[
            'username'  =>$params['username'],
            'nickname'  =>$params['nickname'] ?? $params['username'],
            'mobile'    =>$params['mobile'],
            'email'     =>$params['email'],
            'gender'    =>$params['gender'],
            'birthday'  =>$params['birthday'] ?? '',
            'signature' =>$params['birthday'] ?? '',
            'register_source'=> 0,//管理员添加
            'register_client'=> 1,
            'create_time'=> time(),
        ];
        if (empty($params['password'])){
            $this->setError(3043,'请设置密码！');
            return false;
        }
        $this->startTrans();
        try{
            $id = Db::table($this->table)->insertGetId($data);
            if(!$id){
                $this->setError(3045,'添加用户失败！');
                $this->rollback();
                return false;
            }
            $msg = Db::table('member_mark')->insertAll([
                ['member_id'=>$id, 'token'=>$params['mobile'], 'password'=>$params['password'],'type'=>1],
                ['member_id'=>$id, 'token'=>$params['email'], 'password'=>$params['password'],'type'=>2],
                ['member_id'=>$id, 'token'=>$params['username'], 'password'=>$params['password'],'type'=>3],
            ]);
            if ($msg){
                $this->rollback();
                return false;
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->rollback();
            $this->setError(9999,'添加用户失败！');
            return false;
        }

    }

    /**
     * 获取用户信息
     * @param $memberId
     * @param string $filed
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function memberInfo($memberId,$filed='*'){
        $info = Db::table($this->table)
            ->field($filed)
            ->where(['member_id'=>$memberId])
            ->find();

        return $info;
    }

    /**
     * 更新用户信息
     * @param $memberId
     * @param $params
     * @return bool
     */
    public function memberInfoSave($memberId,$params){
        $data=[
            'username'  =>$params['username'],
            'nickname'  =>$params['nickname'],
            'mobile'    =>$params['mobile'],
            'email'     =>$params['email'],
            'gender'    =>$params['gender'],
            'birthday'  =>$params['birthday'] ?? '',
            'signature' =>$params['birthday'] ?? '',
            'update_time'=> time(),
        ];
        $this->startTrans();
        try{
            $id = Db::table($this->table)->where(['member_id'=>$memberId])->update($data);
            if(!$id){
                $this->setError(3045,'保存用户信息失败！');
                $this->rollback();
                return false;
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->rollback();
            $this->setError(9999,'保存用户信息失败！');
            return false;
        }
    }

    /**
     * 删除用户
     * @param $memberId
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public function deleteMember($memberId){
        if(!Db::table($this->table)->where(['member_id'=>$memberId])->count()){
            $this->setError(3040,'用户已被删除！');
            return false;
        }
        $msg = Db::table($this->table)
            ->where(['member_id'=>$memberId])
            ->delete();
        if(!$msg){
            $this->setError(3041,'删除用户失败！');
            return false;
        }
        return true;
    }

    /**
     * 校验用户密码
     * @param $memberId
     * @param $password
     * @return bool
     */
    public function checkPassword($memberId,$password){
        $msg = Db::table('member_mark')->where(['member_id'=>$memberId,'password'=>$this->pwdMd5($password)])->count();
        if(!$msg){
            return false;
        }
        return true;
    }

    /**
     * 设置账户登录密码
     * @param $memberId
     * @param $newPassword
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public function setPassword($memberId,$newPassword){
        $condition=[
            ['member_id', '=', $memberId],
            ['type', 'in', [1,2,3]],
        ];
        $data=[
            'password' => $this->pwdMd5($newPassword)
        ];
        $msg = Db::table('member_mark')->field('password')->where($condition)->update($data);
        if(!$msg){
            $this->setError(3030,'设置密码失败！');
            return false;
        }
        return true;
    }
}